package core

import groovy.xml.MarkupBuilder

class Colony {

	String name

	int food = Settings.initialFood
	int structure = Settings.initialStructure
	int energy = Settings.initialEnergy
	int materials= Settings.initialMaterials

	List members = []
	List buildings = []

	Random r = new Random(Settings.randomSeed)

	public Colony(String theName) {
		name = theName
	}

	public void produce() {
		buildings.each { Building b ->
			switch( b.type ) {
				case 'FARM':
					food += Settings.foodProdRate
					break
				case 'SOLAR_PLANT':
					energy += Settings.energyProdRate
					break
				case 'MINE':
					materials += Settings.materialProdRate
					break
			}
		}
	}

	public List randomEvents() {
		Events.Types.grep({ 
			r.nextInt(100) < Events.probability[it]
			}) 
	}

	public void processEvents(List randomEvents) {
		randomEvents.each { Events.Types eventType ->
			switch(eventType) {
				case Events.Types.CONTAGIOUS_DISEASE:
				// selects randomly a colony member that gets sick
					if ( members != []) {
						Member m = members[r.nextInt(members.size())]
						m.isSick = true }
					break
				case Events.Types.THUNDER_STRIKE:
				// selects randomly a building that gets damaged
					if (buildings != []) {
						Building b = buildings[r.nextInt(buildings.size())]
						b.health -= (r.nextInt(Settings.thunderMaxDamage)+1)
					}
					break
				case Events.Types.CROP_PEST:
				// the current food available is reduced
					food -= (food * r.nextInt(Settings.cropPestMaxDamagePct) / 100)
					break
			}
		}
	}

	public String toXML() {
		def writer = new StringWriter()
		def builder = new MarkupBuilder(writer)
		builder.colony(name: name, food: food, structure: structure, energy: energy, materials: materials) {
			members() {
				for(Member m in members) {
					member(name: m.name, health: m.health)
				}
			}
			buildings() {
				for(Building b in buildings) {
					building(type: b.type, health: b.health)
				}
			}
		}
		writer.toString()
	}

	public void fromXML(String xml) {
		def colony = new XmlParser().parseText(xml)
		name = colony.attribute("name")
		food = colony.attribute("food").toInteger()
		structure = colony.attribute("structure").toInteger()
		energy = colony.attribute("energy").toInteger()
		materials = colony.attribute("materials").toInteger()
		members = []
		colony.members.member.each { member ->
			Member m = new Member(member.attribute("name"))
			m.health = member.attribute("health").toInteger()
			members += m
		}
		buildings = []
		colony.buildings.building.each { building ->
			Building b = new Building(building.attribute("type"))
			b.health = building.attribute("health").toInteger()
			buildings += b
		}
	}
}
